import React from "react";
import { LgTable, LgTableProps, LgButton, LgSwitch, lgAlert, LgAlertMouldA } from "lancoo-web-ui";
import { Popover } from 'antd';
import moment from "moment";
import { Scrollbars } from 'react-custom-scrollbars';
import styles from "./index.module.scss";
import './LgTable.scss'


const Base = (props) => {
  const userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
  const isManage = sessionStorage.getItem('isManage');
  const alertAQuestion2 = (typeId, innerTypeId) => {
    let alert = lgAlert.show({
      duration: 0,
      content: '确定要删除该公告类型吗？',
      description: '点击"确定"将删除该类型及该类型下的全部公告。',
      isShowCloseBtn: true,
      tipType: 'warning',
      // tipSize: 'small',
      tipSize: 'big',
      tipMouldType: 'A',
      confirmText: "确定",
      closeText: "再想想",
      showCover: true,
      coverZIndex: 1000,
      coverOpacity: 0.25,
      position: { xAxis: '50%', yAxis: '35%', showDirection: 'center', xOffset: '-50%' },
      onConfirm: () => {
        props.delType(typeId, innerTypeId);
        lgAlert.close(alert.index);
      }
    });
    // console.log('alert', alert);

  }

  const alertNotice = (bulletinId, type) => {
    let alert = lgAlert.show({
      duration: 0,
      content: `确定要${type === 'del' ? '删除' : '撤回'}该公告吗？`,
      isShowCloseBtn: true,
      tipType: 'question',
      tipSize: 'small',
      tipMouldType: 'A',
      confirmText: "确定",
      closeText: "再想想",
      showCover: true,
      coverZIndex: 1000,
      coverOpacity: 0.25,
      onConfirm: () => {
        if (type === 'del') {
          props.deleteNotice(bulletinId);
        } else {
          props.callbackNotice(bulletinId);
        }

        lgAlert.close(alert.index);
      }
    });
  }
  const formatRemainingTime = (endTime) => {
    if (!endTime) return '--';

    // 确保日期正确解析（如果原始数据是字符串）
    const end = new Date(endTime);
    const now = new Date();
    const diff = end - now;

    if (diff < 0) return '已过期';

    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const minutes = Math.floor(diff / (1000 * 60));

    if (days > 0) return `${days}天后失效`;
    if (hours > 0) return `${hours}小时后失效`;
    if (minutes > 0) return `${minutes}分钟后失效`;

    return '已过期';  // 小于1分钟的情况
  };

  // console.log('props111', props);
  let data = [];
  let dataOne = {};
  let columns = [
    {
      dataIndex: "state",
      key: "state",
      align: "center",
      render: (value, record, index) => {
        return <>{isManage === '1' ? <>{record.seat === '1' && record.state === '1' ? <i className="top-icon"></i> : ''}<div className={"state-bg state-bg-" + value}>
          <span className={"state state-" + value}>{value == 1 ? '已发布' : '未发布'}</span></div></> : record.readStatus == '1' ? '' : <div className="no-read"></div>}</>
      },
    },
    {
      title: "公告标题",
      dataIndex: "projectName",
      key: "projectName",
      width: isManage !== '1' ? 340 : '',
      render: (value, record) => {
        return <><span className={"project-name project-name-title"} title={value} onClick={
          () => {
            if (record.state == '1' || isManage !== '1') {
              props.openNoticeContent(record.bulletinId)
            } else if (record.state == '0') {
              props.editNotice('edit', record.bulletinId)
            }
          }
        } style={{ fontWeight: record.readStatus === '0' ? 'bold' : '', maxWidth: isManage !== '1' ? 310 : '' }}>{record.haveAttachment === '1' ? <i className="attachment-icon" title="该公告含有附件~"></i> : ''}{value}</span></>;
      },
    },
    {
      title: "类型",
      dataIndex: "projectType",
      key: "projectType",
      width: isManage !== '1' ? 150 : '',
      render: (value) => {
        return <span title={value} className={"project-type"}>{value}</span>;
      },
    },
    {
      title: "发布部门",
      dataIndex: "publishDepartment",
      key: "publishDepartment",
      width: isManage !== '1' ? 150 : '',
      render: (value) => {
        return <span title={value} className={"publish-department"}>{value}</span>;
      },
    },
    isManage === '1' ?
      {
        title: "发布者",
        marginLeft: '29px',
        dataIndex: "publisher",
        key: "publisher",
        className: 'publisher-header',
        render: (value, record) => {
          return <><i className="photo" style={{ backgroundImage: `url(${record.avatarPath})` }}></i><span title={value} className={"publisher"}>{value}</span></>;
        },
      } : {},
    {
      title: "发布时间 ",
      dataIndex: "publishTime",
      key: "publishTime",
      align: "center",
      render: (value, record) => {
        return <div className="publish-time-box">
          <span className={"publish-time"}>{record.state === '1' || isManage !== '1' ? value : '--'}</span>
          {
            record?.displayEndTime ?
              <span className={record.state === '1' ? formatRemainingTime(record?.displayEndTime) !== '已过期' ? "publish-time finish_span" : "publish-time finish_span finish_span_color" :'publish-time'}>{record.state === '1' || isManage !== '1' ? formatRemainingTime(record?.displayEndTime) : ''}</span>
              : ''
          }
        </div>
      },
    },
    {
      title: "操作",
      dataIndex: "operation",
      key: "operation",
      // width: 200,
      render: (value, record) => {

        return (
          <div className={"operation"}>
            <LgButton split shapeType='text' type='info' onClick={
              () => {
                if (record.state == '1' || isManage !== '1') {
                  props.openNoticeContent(record.bulletinId)
                } else if (record.state == '0') {
                  props.editNotice('edit', record.bulletinId)
                }
              }
            }>{record.state == '1' || isManage !== '1' ? '详情' : '编辑'}</LgButton>
            {
              isManage === '1' ?
                <>
                  <LgButton onClick={() => alertNotice(record.bulletinId, (record.state === '1' ? 'callback' : 'del'))} split shapeType='text' type='fail'>{record.state == '1' ? '撤回' : '删除'}</LgButton>
                  {
                    record.state == '1' ?
                      <LgButton onClick={() => props.toTop(record.bulletinId, record.seat)} split shapeType='text' type='info'>{record.seat == '0' ? '置顶' : '取消置顶'}</LgButton> : ''
                  }
                </>
                : ''
            }
          </div>
        );
      },
    },
  ];

  if (props.type === 'typeSet') {

    columns = [
      {
        title: "类型",
        width: 100,
        dataIndex: "projectName",
        key: "projectName",
        className: "type-header",
        render: (value) => {
          return <span className={"project-type project-type-name"}>{value}</span>;
        },
      },
      {
        title: "可查看范围",
        width: 200,
        dataIndex: "canViewResult",
        key: "canViewResult",
        render: (value) => {
          return <span className={"project-name can-view-persons"} title={value} style={{ width: !(userInfo.userType === '6' || (userInfo.userType === '0' && (userInfo.userClass === '2' || userInfo.userClass === '4'))) ? '227px' : '' }} >{value}</span>;
        },
      },
      {
        title: "描述",
        width: 388,
        dataIndex: "remark",
        key: "remark",
        render: (value) => {
          return <span className={"remark"} title={value}>{value}</span>;
        },
      },
      {
        title: "负责人",
        width: 246,
        // marginLeft: '29px',
        dataIndex: "director",
        key: "director",
        render: (value, record) => {
          return <><span className={value.length > 0 ? "director" : "director no-director"} title={record.directorList.length === 0 ? value : ''}>{value.length > 0 ? value : '未设置'}</span>
            {record.directorList.length > 0 ? <span className="director director-num">{record.directorList.length > 1 ? ` 等${record.directorList.length}人` : ''}</span> : ''}
            {record.directorList.length > 1 ? <Popover overlayClassName='popover-item' content={record.content} title="负责人"><i className="director-list"></i></Popover> : ''}</>;
        },
      },
      {
        title: "负责身份类型",
        width: 100,
        dataIndex: "identityResult",
        key: "identityResult",
        render: (value, record) => {
          return <><span className={value.length > 0 ? "director identity-result" : "director no-director"} title={value.length > 0 ? value : ''}>{value.length > 0 ? value : '未设置'}</span></>;
        },
      },
      {
        title: "状态 ",
        // width: 70,
        left: 0,
        dataIndex: "status",
        key: "status",
        align: "left",
        render: (value, record) => {

          return <LgSwitch onClick={() => props.setTypeState(record.typeId, record.innerTypeId, value)} checked={value === '1' ? true : false} />;
        },
      },
      {
        title: "操作",
        dataIndex: "operation",
        key: "operation",
        className: "operation-header",
        // width: 200,
        render: (value, record) => {
          // console.log('record',record);
          return (
            <div className={"operation"}>
              <LgButton split shapeType='text' type='info' onClick={() => { props.editType(record); console.log(value, 'value', record); }}>编辑</LgButton>
              {
                isManage === '1' && record.source === '2' ?
                  <LgButton onClick={() => alertAQuestion2(record.typeId, record.innerTypeId)} split shapeType='text' type='fail'>删除</LgButton>
                  : ''
              }
            </div>
          );
        },
      },
    ];
    if (sessionStorage.getItem('isAdvanced') == 0 && !(userInfo.userType === '6' || (userInfo.userType === '0' && (userInfo.userClass === '2' || userInfo.userClass === '4')))) {
      columns.splice(5)
    }
    if (props.typeList) {
      props.typeList.forEach((element, index) => {
        // console.log('element',element);

        let nameArr = [], identityArr = [];
        if (element.directorList.length > 0) {
          element.directorList.forEach(item => {
            nameArr.push(item.userName);
          })
          // } else if (element.directorIdentityList && element?.directorIdentityList.length > 0) {
        }
        if (element.directorIdentityList && element?.directorIdentityList.length > 0) {
          element.directorIdentityList.forEach(item => {
            if (item.identityCode === 'IC0001') return
            identityArr.push(item.identityName);
            // nameArr.push(item.identityName);
          })
        }
        // .slice(0,20)
        let content = element.directorList.map((item, index) =>
        (
          <div style={{ display: 'flex', margin: '0 8px 8px 0' }}>
            <i className="photo" style={{ backgroundImage: `url(${item.avatarPath})` }}></i>
            <p>{item.userName}</p>
            <p>({item.userId})</p>
          </div>
        ));

        let result = "";
        nameArr.forEach((item, index) => {
          result += item;
          if (index !== nameArr.length - 1) {
            result += "、";
          }
        });
        let identityResult = "";
        identityArr.forEach((item, index) => {
          identityResult += item;
          if (index !== identityArr.length - 1) {
            identityResult += "、";
          }
        });

        let canViewPeople = [];
        element.scope.forEach(item => {
          switch (item) {
            case '0': canViewPeople.push('管理员');
              break;
            case '1': canViewPeople.push('教师');
              break;
            case '2': canViewPeople.push('学生');
              break;
            case '3': canViewPeople.push('家长');
              break;
            case '11': canViewPeople.push('其他');
              break;
            default:
              break;
          }
        })
        let canViewResult = canViewPeople.join('、')

        dataOne = {
          key: index,
          typeId: element.typeId,
          innerTypeId: element.innerTypeId,
          // bulletinId: element.typeId || element.innerTypeId,
          projectName: element.typeName,
          canViewPeople: element.scope,
          canViewResult,
          remark: element.remark,
          director: result,
          status: element.state,
          directorList: element.directorList,
          content,
          source: element.source,
          directorIdentityList: element.directorIdentityList,
          identityResult
        }
        data.push(dataOne);
        return data;
      });
    }
  } else if (props.type === 'noticeList') {
    if (props.noticeList) {
      props.noticeList.forEach((item, index) => {

        dataOne = {
          key: index,
          state: item.status,
          bulletinId: item.bulletinId,
          typeId: item.typeId,
          innerTypeId: item.innerTypeId,
          projectName: item.title,
          projectType: item.typeName,
          publishDepartment: item.departmentName,
          publisher: item.userName,
          publishTime: moment(item.releaseTime).format('YYYY-MM-DD HH:mm'),
          avatarPath: item.avatarPath,
          seat: item.seat,
          readStatus: item.readStatus,
          haveAttachment: item.haveAttachment,
          displayEndTime: item.displayEndTime,
        }
        data.push(dataOne);
        return data;
      })

      // console.log('props.noticeList', props.noticeList);

    }
  }



  return (
    <div>
      {/* <h4>基础表格</h4> */}
      <Scrollbars autoHeight autoHeightMax={592} autoHide autoHideTimeout={100}>
        <LgTable columns={columns} data={data} emptyText={'没有数据，到别处看看呢~'} />
      </Scrollbars>
    </div>
  );
};

export default Base;